package com.jtbd.handler;

import com.jtbd.dto.UserAuthDetailsEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class GetSecurityUserHandler {
    /**
     * 获取当前安全认证用户的ID
     *
     * @return Long 用户ID，如果无法获取则返回null
     */
    public static Long getSecurityUserId() {
        // 从安全上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();

        // 判断认证主体是否为UserAuthDetailsEntity类型，如果是则返回用户ID
        if (object instanceof UserAuthDetailsEntity userDetails) {
            return userDetails.getUid();
        }

        return null;
    }

    /**
     * 获取当前安全认证用户
     *
     * @return UserAuthDetailsEntity
     */
    public static UserAuthDetailsEntity getSecurityUser() {
        // 从安全上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object object = authentication.getPrincipal();

        // 判断认证主体是否为UserAuthDetailsEntity类型，如果是则返回用户ID
        if (object instanceof UserAuthDetailsEntity userDetails) {
            return userDetails;
        }

        return null;
    }
}
